<template>
  <div class="register">
    <!-- 顶部内容 -->
    <section class="header">
      <div class="flex-between header_box">
<!--        <img src="~@/assets/images/logo.png" alt="">-->
        <p>已有账号？<el-button type="text" @click="toLogin">去登录</el-button></p>
      </div>
    </section>

    <section class="box">

      <h6>交通地灾云注册</h6>
      <el-steps :active="stepActive" simple class="m-b-40 register_step" finish-status="success">
        <el-step title="单位类型选择" ></el-step>
        <el-step title="单位信息"></el-step>
        <el-step title="单位负责人"></el-step>
        <el-step title="证明材料"></el-step>
        <el-step title="提交" ></el-step>
      </el-steps>

      <!-- 步骤一  选择单位类型 -->
      <div v-show="stepActive === 0" class="box_wrap">
        <el-select v-model="form.platformType" placeholder="选择单位类型" style="margin:32px 0 120px">
          <el-option
            v-for="item in EnumUnitTypeList"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>

        <el-button @click="firstStepValidator" size="medium" type="primary">下一步</el-button>
      </div>

      <!-- 步骤二  单位信息 -->
      <div v-show="stepActive === 1"  class="box_wrap">
        <!-- form表单 -->

        <form-unit v-model="form" ref="formUnit" :queryDictData="queryDictData"></form-unit>

        <span>
          <el-button size="medium" type="primary" plain @click="stepActive--">上一步</el-button>
          <el-button size="medium" type="primary"  @click="validatorForm('formUnit')">下一步</el-button>
        </span>
      </div>

      <!-- 步骤三 单位负责人 -->
      <div v-show="stepActive === 2"  class="box_wrap">

        <form-principal v-model="form" ref="formPrincipal"></form-principal>
        <span>
          <el-button size="medium" type="primary" plain @click="stepActive--">上一步</el-button>
          <el-button size="medium" type="primary"  @click="validatorForm('formPrincipal')">下一步</el-button>
        </span>

      </div>

      <!-- 步骤四 证明材料 -->
      <div v-show="stepActive === 3"  class="box_wrap">
        <div class="tip">
          <p>请提供公司盖章相关证明</p>
          <p>支持jpg、png、gif、jpeg格式的图片</p>
        </div>
        <upload-img v-model="form.voucherList"></upload-img>

        <span class="m-t-24">
          <el-button size="medium" type="primary" plain @click="stepActive--">上一步</el-button>
          <el-button size="medium" type="primary"  @click="checkImg">下一步</el-button>
        </span>
      </div>

      <!-- 步骤五 提交 -->
      <div v-show="stepActive === 4"  class="box_wrap">

        <span class="m-t-24">
          <el-form label-position="right" ref="serviceForm" :model="form" label-suffix="：" label-width="0">
            <el-form-item label="" prop="checkRadio" :rules="{required: true, message: '请阅读勾选同意协议'}">
              <div class="service_check">
                <el-checkbox v-model="form.checkRadio" :false-label="null" :true-label="1"></el-checkbox>
                <router-link class="service_router" to="">久感边坡云服务条款</router-link>
              </div>
            </el-form-item>
          </el-form>
          <el-button size="medium" type="primary" plain @click="stepActive--" :loading="isLoading">上一步</el-button>
          <el-button size="medium" type="success"  @click="validatorServiceForm" :loading="isLoading">提交</el-button>
        </span>
      </div>
    </section>

  </div>
</template>

<script>
import FormUnit from './modules/form-unit'
import FormPrincipal from './modules/form-principal'
import { getDictData } from '@/services/model/common'
import UploadImg from './modules/upload-img'
import { register } from '@/services/model/login'
import md5 from 'js-md5'

// 用户信息缓存
const USER_INFO = 'userInfo'
// 用户当前的操作步骤
const USER_ACTIVE_STEP = 'userActiveStep'

export default {
  components: { FormUnit, FormPrincipal, UploadImg },
  data () {
    return {
      // 单位请上传文件类型
      EnumUnitTypeList: [],
      // 当前步骤条进度
      stepActive: sessionStorage.getItem(USER_ACTIVE_STEP) ? JSON.parse(sessionStorage.getItem(USER_ACTIVE_STEP)) : 0,
      // 用户提交数据表单
      form: sessionStorage.getItem(USER_INFO) ? JSON.parse(sessionStorage.getItem(USER_INFO)) : {},
      // 接口是否正在加载
      isLoading: false
    }
  },
  watch: {
    // 由于表单内容过多，添加sesstion缓存
    form: {
      handler (value) {
        sessionStorage.setItem(USER_INFO, JSON.stringify(value))
      },
      deep: true
    },
    stepActive (value) {
      sessionStorage.setItem(USER_ACTIVE_STEP, JSON.stringify(value))
    }
  },
  methods: {
    // 第一步校验
    firstStepValidator () {
      if (this.form.platformType === null || this.form.platformType === '') {
        this.$message.error('请刷新页面，重新加载数据')
        return false
      }
      ++this.stepActive
    },
    // 校验勾选协议
    validatorServiceForm () {
      this.$refs.serviceForm.validate((valid) => {
        valid && this.submitForm()
      })
    },
    // 表单提交
    async submitForm () {
      let { voucherList, region, password } = this.form
      voucherList = voucherList?.map(x => x.response.data.path)
      region = region.join('-')
      password = md5(password)
      let form = { ...this.form, voucherList, region, password, repeat: '' }
      this.isLoading = true
      try {
        await register(form)
        this.isLoading = false
        this.stepActive = 0
        this.form = {}
        this.$confirm('注册信息审核中，请等待短信通知。', '提示', {
          confirmButtonText: '去登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.toLogin()
        })
      } catch (error) {
        this.isLoading = false
      }
    },
    // 去登录
    toLogin () {
      // 清楚缓存信息
      sessionStorage.removeItem(USER_INFO)
      // 清楚记录的步骤条
      sessionStorage.removeItem(USER_ACTIVE_STEP)
      this.$router.push('/login')
    },
    // 图片必填验证
    checkImg () {
      if (!this.form.voucherList?.length) {
        this.$message.error('请上传证明材料')
        return false
      }
      this.stepActive++
    },
    // 表单校验
    validatorForm (name) {
      this.$refs[name]._validatorForm().then((res) => {
        this.stepActive++
      })
    },
    // 通用获取枚举方法
    async queryDictData (enumName, model) {
      const { data } = await getDictData({ enumName })
      if (model) this[model] = data || []
      return data || []
    }
  },
  created () {
    // 默认设置第一个值
    this.queryDictData('EnumUnitType', 'EnumUnitTypeList').then(res => {
      if (!this.form.platformType) this.$set(this.form, 'platformType', res[0]?.code)
    })
  }
}
</script>

<style lang="less" scoped>
  .el-button--text {
    color:  #4caf50;
  }
  .register {
    position: relative;
    height: 100%;
    .header {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 60px;
      background-color: #ffffff;
      .header_box {
        height: 100%;
        width: 900px;
        margin: 0 auto;
        img {
          width: 200px;
        }
      }
    }

    .box {
      position: relative;
      top: 46%;
      transform: translateY(-50%);
      margin: 0 auto;
      width: 900px;
      min-height: 400px;
      background-color: #fff;
      box-shadow: 0 0 5px 3px rgba(0,0,0,.03);
      border-radius: 8px;
      padding: 20px;
      .box_wrap {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      & > h6 {
        text-align: center;
        font-size: 20px;
        padding: 40px 0 28px;
      }
      /deep/.register_step {
        width: 800px;
        padding: 10px 3%;
        .is-simple:not(:last-of-type) .el-step__title {
          max-width: none;
        }
        .el-step__title.is-wait {
          color: #999;
        }
        .el-step__head.is-finish .el-step__icon {
          border-width: 8px;
        }
      }
      .el-form {
        width: 560px;
      }
    }
  }

.fade-enter-active, .fade-leave-active {
  transition: all 1s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.fade-leave-to
/* .list-leave-active for below version 2.1.8 */ {
  transform: translateX(-30px);
}
.tip {
  font-size: 18px;
  color: #999;
  margin-left: 25px;
  margin-bottom: 20px;
  p {
    line-height: 26px;
  }
}
.service_check {
  .el-checkbox {
    margin-right: 10px;
  }
  .service_router {
    color: royalblue;
  }
  .el-button--text{
    color: #228af5;
  }
}
</style>
